import {
  Controller,
  Post,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { JwtAuthGuard } from 'src/common/guard/jwt-auth.guard';
import { simpleUUIDGenerator } from 'src/utils';
import { join, parse } from 'path';

@Controller('api/upload')
@UseGuards(JwtAuthGuard)
export class UploadController {
  @Post()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: join(__dirname, '../../../static'), //存储在根目录的static文件夹下
        filename: (req, file, cb) => {
          const fileName: string = simpleUUIDGenerator(); //添加随机uuid
          const extension: string = parse(file.originalname).ext;
          cb(null, `${fileName}${extension}`);
        },
      }),
    }),
  )
  uploadFile(@UploadedFile() file: Express.Multer.File) {
    return {
      name: file.filename,
      path: file.filename,
    };
  }
}
